﻿using EONFULLSIN2.Models.Dto.Device;
using EONFULLSIN2.Services.DB;
using EONFULLSIN2.Services.Device.DIOModelA;
using EONFULLSIN2.Services.Device.DIOModelB;
using EONFULLSIN2.Services.Device.JuYing;
using EONFULLSIN2.Services.Device.ZhongChuangZhiHe;
using EONFULLSIN2.Services.Device.ZhuoLan;
using EONFULLSIN2.Services.Device.ZMoiton;
using EONFULLSIN2.Services.Message;
using EONFULLSIN2.ViewModelBase;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace EONFULLSIN2.ViewModel
{
    public class DeviceManagerViewModel : NavigationViewModel
    {
        private readonly IJuYingModbusService _juYingModbusService;
        private readonly IZhuoLanModbusService _zhuoLanModbusService;
        //private readonly IAdamComDIOModelAService _adamComDIOModelAService;
        //private readonly IAdamComDIOModelBService _adamComDIOModelBService;
        private readonly IZMoitonService _zMoitonService;
        private readonly IZczhModbusService _zczhModbusService;

        private readonly DispatcherTimer readDataTimer;

        public DeviceManagerViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IMessageService messageBox,
            IDbOperate<IFreeSqlMainContext> mainDbOperate,
            IEventAggregator eventAggregator,
            IJuYingModbusService juYingModbusService,
            IZhuoLanModbusService zhuoLanModbusService,
            IZMoitonService zMoitonService,
            IZczhModbusService zczhModbusService
            //IAdamComDIOModelAService adamComDIOModelAService,
            //IAdamComDIOModelBService adamComDIOModelBService
            )
            : base(regionManager, dialog, messageBox, eventAggregator, mainDbOperate) {

            this._juYingModbusService = juYingModbusService;
            this._zhuoLanModbusService = zhuoLanModbusService;
            //this._adamComDIOModelAService = adamComDIOModelAService;
            //this._adamComDIOModelBService = adamComDIOModelBService;
            this._zMoitonService = zMoitonService;
            this._zczhModbusService = zczhModbusService;

            // 使用Timer轮询获取数据
            readDataTimer = new DispatcherTimer();
            readDataTimer.Interval = TimeSpan.FromSeconds(0.5);
            readDataTimer.Tick += PollingReadDataAsync;
            readDataTimer.Start();
            //readDataTimer = new Timer(PollingReadDataAsync, null, 1000, 5000);
        }

        #region Props
        private ObservableCollection<SensorItemDto> _temperatureSensorItems = new ObservableCollection<SensorItemDto>();

        public ObservableCollection<SensorItemDto> TemperatureSensorItems {
            get { return _temperatureSensorItems; }
            set { _temperatureSensorItems = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<SensorItemDto> _pressureSensorItems = new ObservableCollection<SensorItemDto>();

        public ObservableCollection<SensorItemDto> PressureSensorItems {
            get { return _pressureSensorItems; }
            set { _pressureSensorItems = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<SensorItemDto> _currentSensorItems = new ObservableCollection<SensorItemDto>();

        public ObservableCollection<SensorItemDto> CurrentSensorItems {
            get { return _currentSensorItems; }
            set { _currentSensorItems = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<SensorItemDto> _voltageSensorItems = new ObservableCollection<SensorItemDto>();

        public ObservableCollection<SensorItemDto> VoltageSensorItems {
            get { return _voltageSensorItems; }
            set { _voltageSensorItems = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<SensorItemDto> _iOMdoelSensorItems = new ObservableCollection<SensorItemDto>();

        public ObservableCollection<SensorItemDto> IOMdoelSensorItems {
            get { return _iOMdoelSensorItems; }
            set { _iOMdoelSensorItems = value; base.RaisePropertyChanged(); }
        }
        #endregion

        #region Commands

        #endregion

        #region Methods
        /// <summary>
        /// 轮询获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PollingReadDataAsync(object? sender, EventArgs e)
        {
            #region 聚英设备
            if (_juYingModbusService.IsConnect)
            {
                try
                {
                    var sensorItemDtos = await _juYingModbusService.GetSensorDataAsync();
                    var temperatureSensorItemsTemp = new ObservableCollection<SensorItemDto>(sensorItemDtos.Where(o => o.Type == Models.Enum.eSensorTypeEnum.Temperature).ToList());
                    if (temperatureSensorItemsTemp != null && temperatureSensorItemsTemp.Count > 0) {
                        if (TemperatureSensorItems.Count == 0) {
                            TemperatureSensorItems.AddRange(temperatureSensorItemsTemp);
                        } else {
                            for (int i = 0; i < TemperatureSensorItems.Count; i++) {
                                TemperatureSensorItems[i].Value = temperatureSensorItemsTemp[i].Value;
                            }
                        }
                    }
                    var pressureSensorItemsTemp = new ObservableCollection<SensorItemDto>(sensorItemDtos.Where(o => o.Type == Models.Enum.eSensorTypeEnum.Pressure).ToList());
                    if (pressureSensorItemsTemp != null && pressureSensorItemsTemp.Count > 0) {
                        if (PressureSensorItems.Count == 0) {
                            PressureSensorItems.AddRange(pressureSensorItemsTemp);
                        } else {
                            for (int i = 0; i < PressureSensorItems.Count; i++) {
                                PressureSensorItems[i].Value = pressureSensorItemsTemp[i].Value;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _runLogUIEvent.Publish($"{_juYingModbusService.IpAddress}:{_juYingModbusService.Port},{ex.Message}");
                }
            }
            //else
            //{
            //    _runLogUIEvent.Publish($"{_juYingModbusService.IpAddress}:{_juYingModbusService.Port}(JUYING),设备未连接");
            //}
            #endregion

            #region 卓岚设备
            //if (_zhuoLanModbusService.IsConnect)
            //{
            //    try
            //    {
            //        var res = await _zhuoLanModbusService.GetDataAsync();
            //        Debug.WriteLine($"==> zhuoLanModbusService 获取结果：{res}");
            //    }
            //    catch (Exception ex)
            //    {
            //        _runLogUIEvent.Publish($"{_zhuoLanModbusService.IpAddress}:{_zhuoLanModbusService.Port},{ex.Message}");
            //    }
            //}
            //else
            //{
            //    _runLogUIEvent.Publish($"{_zhuoLanModbusService.IpAddress}:{_zhuoLanModbusService.Port}(ZHUOLAN),设备未连接");
            //}

            #endregion

            #region MyRegion
            if (_zczhModbusService.IsConnect) {
                try {
                    var sensorItemDtos = await _zczhModbusService.GetSensorDataAsync();
                    var currentSensorItemsTemp = new ObservableCollection<SensorItemDto>(sensorItemDtos.Where(o => o.Type == Models.Enum.eSensorTypeEnum.Current).ToList());
                    if (currentSensorItemsTemp != null && currentSensorItemsTemp.Count > 0) {
                        if (CurrentSensorItems.Count == 0) {
                            CurrentSensorItems.AddRange(currentSensorItemsTemp);
                        } else {
                            for (int i = 0; i < CurrentSensorItems.Count; i++) {
                                CurrentSensorItems[i].Value = currentSensorItemsTemp[i].Value;
                            }
                        }
                    }

                   var voltageSensorItemsTemp = new ObservableCollection<SensorItemDto>(sensorItemDtos.Where(o => o.Type == Models.Enum.eSensorTypeEnum.Voltage).ToList());
                    if (voltageSensorItemsTemp != null && voltageSensorItemsTemp.Count > 0) {
                        if (VoltageSensorItems.Count == 0) {
                            VoltageSensorItems.AddRange(voltageSensorItemsTemp);
                        } else {
                            for (int i = 0; i < VoltageSensorItems.Count; i++) {
                                VoltageSensorItems[i].Value = voltageSensorItemsTemp[i].Value;
                            }
                        }
                    }
                } catch (Exception ex) {
                    _runLogUIEvent.Publish($"{_zczhModbusService.IpAddress}:{_zczhModbusService.Port},{ex.Message}");
                }
            }
            #endregion

            #region 获取IO模块数据
            if (_zMoitonService.IsConnect) {
                try {
                    var ioStatus = await _zMoitonService.GetSensorOutPutStatusAsync();
                    if (ioStatus != null && ioStatus.Count > 0) {
                        if (IOMdoelSensorItems.Count == 0) {
                            IOMdoelSensorItems.AddRange(ioStatus);
                        } else {
                            for (int i = 0; i < IOMdoelSensorItems.Count; i++) {
                                IOMdoelSensorItems[i].Value = ioStatus[i].Value;
                            }
                        }
                    } else {
                        _runLogUIEvent.Publish($"{_zMoitonService.IpAddress},(ZMoiton),未获取到数据");
                    }
                } catch (Exception ex) {
                    _runLogUIEvent.Publish($"{_zMoitonService.IpAddress},(ZMoiton),{ex.Message}");
                }
            }
            //else {
            //    _runLogUIEvent.Publish($"{_zMoitonService.IpAddress},(ZMoiton),未连接");
            //}

            #region Adam
            //IOMdoelSensorItems.Clear();
            ////IO模块A数据
            //if (_adamComDIOModelAService.IsOpen)
            //{
            //    try
            //    {
            //        var res = await _adamComDIOModelAService.GetDOChannelStatusAsync();
            //        if (res != null && res.Count > 0)
            //        {
            //            IOMdoelSensorItems.AddRange(res);
            //        }
            //        else
            //        {
            //            _runLogUIEvent.Publish($"{_adamComDIOModelAService.COMName},(AdamComDIOModelA),未获取到数据");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        _runLogUIEvent.Publish($"{_adamComDIOModelAService.COMName},(AdamComDIOModelA),{ex.Message}");
            //    }
            //}
            //else
            //{
            //    _runLogUIEvent.Publish($"{_adamComDIOModelAService.COMName},(AdamComDIOModelA),端口未打开");
            //}

            ////IO模块B数据
            //if (_adamComDIOModelBService.IsOpen)
            //{
            //    try
            //    {
            //        var res = await _adamComDIOModelBService.GetDOChannelStatusAsync();
            //        if (res != null && res.Count > 0)
            //        {
            //            IOMdoelSensorItems.AddRange(res);
            //        }
            //        else {
            //            _runLogUIEvent.Publish($"{_adamComDIOModelBService.COMName},(AdamComDIOModelB),未获取到数据");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        _runLogUIEvent.Publish($"{_adamComDIOModelBService.COMName},(AdamComDIOModelB),{ex.Message}");
            //    }
            //}
            //else
            //{
            //    _runLogUIEvent.Publish($"{_adamComDIOModelBService.COMName},(AdamComDIOModelB),端口未打开");
            //}
            #endregion

            #endregion
        }


        protected override void OnViewLoaded()
        {
            TemperatureSensorItems.Clear();
        }
        #endregion
    }
}
